package main

import (
	"bufio"
	"bytes"
	"fmt"
	"github.com/pion/rtp"
	"github.com/pion/rtp/codecs"
	"net"
	"os"
	"time"
)

func main() {
	file, err := os.Open("/Users/frank/gitee/joy4/format/h264/Sample.h264")
	if err != nil {
		fmt.Println(err)
		return
	}

	defer file.Close()

	scanner := bufio.NewScanner(file)
	buf := make([]byte, 0, 64*1024)
	scanner.Buffer(buf, 1024*1024)
	scanner.Split(func(data []byte, atEOF bool) (advance int, token []byte, err error) {
		if atEOF && len(data) == 0 {
			return 0, nil, nil
		}

		if i := bytes.Index(data, []byte{0, 0, 0, 1}); i >= 0 {
			return i + 4, data[0:i], nil
		}

		// If we're at EOF, we have a final, non-terminated line. Return it.
		if atEOF {
			return len(data), data, nil
		}
		// Request more data.
		return 0, nil, nil
	})

	// rtp 发送
	out, err := net.Dial("udp", "127.0.0.1:1234")
	defer out.Close()
	if err != nil {
		os.Exit(1)
	}

	packetizer := rtp.NewPacketizer(1200, 96, 1111, &codecs.H264Payloader{}, rtp.NewRandomSequencer(), 90000)

	for scanner.Scan() {
		nalu := scanner.Bytes()
		if len(nalu) > 0 {
			//fmt.Printf("start:%v\n",nalu[:4])
			t := nalu[0] & 0x1f
			//fmt.Printf("stop:%v\n",nalu[len(nalu)-4:])
			fmt.Printf("t:%d size:%d\n", t, len(nalu))
			rtps := packetizer.Packetize(nalu, 90000/25)
			for _, v := range rtps {
				fmt.Println(v.SequenceNumber, v.Timestamp)
				data, _ := v.Marshal()
				out.Write(data)
			}

			time.Sleep(40 * time.Millisecond)

		}
	}
}
